package com.xzy.demo.juc.locks;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xzy
 * @date 2021/3/21 8:07
 * 说明：线程 操作 资源类
 */

public class SaleTicketDemo01 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {for (int i = 0; i < 40; i++){ticket.sale();}}, "A").start();
        new Thread(() -> {for (int i = 0; i < 40; i++){ticket.sale();}}, "B").start();
        new Thread(() -> {for (int i = 0; i < 40; i++){ticket.sale();}}, "C").start();
    }
}

class Ticket {
    private int number = 30;
    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + " 卖出票 " + (number--) + " 剩余 " + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

@FunctionalInterface
interface MethodUtil{
    void add(int a,int b);

    default int mul(int a,int b){ return a*b; }

    static int div(int a,int b){return a/b;}
}